#include <iostream>
#include <time.h>

// 构建一个堆
void MaxHeap(int *a, int n, int i)
{
    int left = 2 * i + 1;
    int right = 2 * i + 2;
    int Max = i;
    if (left < n && a[left] > a[Max])
        Max = left;
    if (right < n && a[right] > a[Max])
        Max = right;

    if (Max != i)
    {
        std::swap(a[i], a[Max]);
        MaxHeap(a, n, Max);
    }
}

void HeapSort(int *a, int n)
{
    // 第一个非叶子节点
    for (int i = n / 2 - 1; i >= 0; i--)
    {
        MaxHeap(a, n, i);
    }
    for(int i= n-1; i>= 0; i--)
    {
        std::swap(a[0],a[i]); //始终把根放到最后
        MaxHeap(a, i, 0);
    }
}

int main()
{
    srand(time(nullptr));
    int a[20];
    for (int i = 0; i < 20; i++)
    {
        a[i] = rand() % 100 + 1;
    }
    for(int i=0; i<20; i++)
    {
        std::cout<<a[i]<<" ";
    }
    std::cout<<std::endl;

    HeapSort(a, 20);
    for(int i=0; i<20; i++)
    {
        std::cout<<a[i]<<" ";
    }
    std::cout<<std::endl;
    return 0;
}